package articles_api

import (
	"context"
	"encoding/json"
	"gin_study_blog/common"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"github.com/gin-gonic/gin"
	"github.com/olivere/elastic/v7"
)

// FullTextSearchView 全文搜索
func (ArticlesApi) FullTextSearchView(c *gin.Context) {
	var cr models.PageInfo
	_ = c.ShouldBindQuery(&cr)

	boolQuery := elastic.NewBoolQuery()

	if cr.Key != "" {
		boolQuery.Must(elastic.NewMultiMatchQuery(cr.Key, "title", "body"))
	}

	res, err := common.EsClient.Search(models.FullTextModel{}.Index()).
		Query(boolQuery).
		Highlight(elastic.NewHighlight().Field("body")).
		Do(context.Background())
	if err != nil {

		return
	}

	count := res.Hits.TotalHits.Value
	fullTextModel := make([]models.FullTextModel, 0)

	for _, hit := range res.Hits.Hits {
		var model models.FullTextModel
		err = json.Unmarshal(hit.Source, &model)
		body, ok := hit.Highlight["body"]
		if ok {
			model.Body = body[0]
		}
		fullTextModel = append(fullTextModel, model)
	}
	http.IsOkWithList(fullTextModel, count, c)
}
